<template>
  <WebGLCanvas :id="id"/>
</template>

<script setup lang="ts">
  import { Engine, Scene, ArcRotateCamera, Vector3,
    HemisphericLight, PointLight, MeshBuilder
  } from '@babylonjs/core'

  const id = 'parametric-shapes'
  useHead({
    title: '具有参数化形状的物体'
  })

  const initBabylon = () => {
    // 初始化canvas
    const canvas = document.querySelector<HTMLCanvasElement>(`#${id}`)
    if (!canvas) {
      throw new Error('Canvas not found.')
    }
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    // 初始化babylon 3D Engine, 开启抗锯齿
    /** 
     * “抗锯齿(英语:anti-aliasing,简称AA),
     * 也译为边缘柔化、消除混叠、抗图像折叠有损等。
     * 它是一种消除显示器输出的画面中图物边缘出现凹凸锯齿的技术,
     * 那些凹凸的锯齿通常因为高分辨率的信号以低分辨率表示或无法准确运算出3D图形坐标定位时所导致的图形混叠(aliasing)而产生的,
     * 反锯齿技术能有效地解决这些问题。
     */
    const engine = new Engine(canvas, true)

    // 创建一个场景
    const scene = new Scene(engine)
    // 添加一个相机
    const camera = new ArcRotateCamera(
      'camera',
      Math.PI / 2,
      Math.PI / 2,
      2,
      new Vector3(0, 0, 10),
      scene
    )
    // 绑定鼠标事件
    camera.attachControl(canvas, true)
    // 添加一组灯光到场景
    const light1 = new HemisphericLight('light1', new Vector3(1, 1, 0), scene)
    const light2 = new PointLight('light2', new Vector3(0, 1, -1), scene)
    // 添加一个球体到场景中
    // const sphere = MeshBuilder.CreateSphere('sphere', {diameter: 1}, scene)
    // sphere.position = new Vector3(0, 0, 0)
    
    // 线条Lines
    const points = new Array<Vector3>(
      new Vector3(0, 0, 0),
      new Vector3(0, 1, 1),
      new Vector3(0, 1, 0)
    )
    const lines = MeshBuilder.CreateLines(
      'lines',
      {
        points
      },
      scene
    )
    // lines.rotation = new Vector3(Math.PI/180, Math.PI/180, Math.PI/180)
    // lines.rotation.x = Math.PI/180
    lines.rotation.y = Math.PI/180
    // lines.rotation.z = Math.PI/180

    // 最后一步调用engine的runRenderLoop方案，
    // 执行scene.render()，让我们的3d场景渲染起来
    engine.runRenderLoop(() => {
      scene.render()
    })

    // 监听浏览器改变大小的事件，通过调用engine.resize()来自适应窗口大小
    window.addEventListener('resize', () => {
      engine.resize()
    })
  }

  onMounted(() => {
    initBabylon()
  })
</script>